
#ifndef WISHMASTER_RECAPTCHAFETCHER_IMPL_H
#define WISHMASTER_RECAPTCHAFETCHER_IMPL_H

#include <QObject>
#include "log.h"
#include "network/connector.h"
#include "network/httprequest.h"
#include "components/threadid.h"
#include "components/chan.h"

namespace Wishmaster
{
	class RecaptchaFetcherImpl : public QObject
	{
		Q_OBJECT
	public:
		RecaptchaFetcherImpl()
		{
		}

		void setConnector(Connector* connector)
		{
			m_connector = connector;
		}

		void setParams(const QVariantMap& params)
		{
			for(QVariantMap::const_iterator it = params.begin(); it != params.end(); ++it)
			{
				if(it.key() == "recaptcha_key")
				{
					m_recaptchaKey = it.value().toString();
				}
			}
		}

		void fetchCaptcha(const ThreadId& threadId)
		{
			QString path = "/recaptcha/api/challenge?k=" + m_recaptchaKey;
			RequestPtr rq = m_connector->makeRequest("www.google.com", path); // FIXME hardcoded
			m_connector->connectRequest(this, SLOT(challenge(RequestPtr,QByteArray)), 0, rq);
			m_connector->queue(rq);
			m_threadId = threadId;
		}

		void processRequest(const PostDescriptor& post, const QString& captcha, const RequestPtr& request)
		{
			HttpRequestPtr httprequest = request.dynamicCast<HttpRequest>();
			if(!httprequest)
				return;
			httprequest->addPostField("recaptcha_challenge_field", m_challenge);
			httprequest->addPostField("recaptcha_response_field", captcha);
		}

	signals:
		void captcha(const ThreadId& threadId, const QByteArray& arr);

	private slots:
		void challenge(const RequestPtr& request, const QByteArray& arr)
		{
			QString str(arr);
			QRegExp rx("challenge\\s*:\\s*'([^']*)'");
			if(rx.indexIn(str) < 0)
			{
				log(llError, "recaptchafetcher: Unable to locate challenge");
				return;
			}
			m_challenge = rx.cap(1);
			log(llDebug, "Challenge: %s", qPrintable(m_challenge));

			QString path = "/recaptcha/api/image?c=" + m_challenge;
			RequestPtr rq = m_connector->makeRequest("www.google.com", path); // FIXME hardcoded
			m_connector->connectRequest(this, SLOT(slot_captcha(RequestPtr,QByteArray)), 0, rq);
			m_connector->queue(rq);
		}

		void slot_captcha(const RequestPtr& request, const QByteArray& arr)
		{
			emit captcha(m_threadId, arr);
		}

	private:
		Connector* m_connector;
		QString m_recaptchaKey;
		QString m_challenge;
		ThreadId m_threadId;
	};
}

#endif

